<template>
  <el-dialog v-model="dialogVisible" :title="isEdit ? '修改商品' : '添加商品'" width="90%" :before-close="handleClose"
    destroy-on-close class="product-dialog" style="max-width: 600px">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="90px" class="product-form">
      <!-- 商品名称 -->
      <el-form-item label="商品名称" required prop="productName">
        <el-input v-model="formData.productName" placeholder="请输入商品名称" clearable />
      </el-form-item>

      <!-- 商品分类 -->
      <el-form-item label="商品分类" required prop="category">
        <el-select v-model="formData.category" placeholder="请选择商品分类" style="width: 100%" clearable>
          <el-option v-for="item in cateData" :key="item.id" :label="item.title" :value="item.id" />
          <!-- <el-option label="服装鞋帽" value="服装鞋帽" />
          <el-option label="家居用品" value="家居用品" />
          <el-option label="食品饮料" value="食品饮料" />
          <el-option label="美妆护肤" value="美妆护肤" />
          <el-option label="运动户外" value="运动户外" /> -->
        </el-select>
      </el-form-item>

      <!-- 商品描述 -->
      <el-form-item label="商品描述" required prop="description">
        <el-input v-model="formData.description" type="textarea" placeholder="请输入商品描述" :rows="3" maxlength="200"
          show-word-limit />
      </el-form-item>

      <!-- 商品图片 -->
      <el-form-item label="商品图片" required prop="productImage">
        <div class="image-upload-container">
          <el-upload class="image-uploader" :show-file-list="false" :on-change="handleMainImageChange"
            :before-upload="beforeImageUpload" action="#" :auto-upload="false">
            <div class="upload-area" v-if="!formData.productImage">
              <el-icon class="upload-icon">
                <Plus />
              </el-icon>
              <div class="upload-text">点击上传主图</div>
            </div>
            <img v-else :src="formData.productImage" class="uploaded-image" alt="商品图片" />
          </el-upload>
        </div>
      </el-form-item>

      <!-- 商品轮播 -->
      <el-form-item label="商品轮播" prop="carouselImages">
        <div class="carousel-upload-container">
          <div class="carousel-images">
            <div v-for="(image, index) in formData.carouselImages" :key="index" class="carousel-item">
              <img :src="image" class="carousel-image" alt="轮播图" />
              <div class="carousel-overlay">
                <el-icon @click="removeCarouselImage(index)" class="remove-icon">
                  <Close />
                </el-icon>
              </div>
            </div>
          </div>
          <el-upload class="carousel-uploader" :show-file-list="false" :on-change="handleCarouselImageChange"
            :before-upload="beforeImageUpload" action="#" :auto-upload="false">
            <div class="upload-area">
              <el-icon class="upload-icon">
                <Plus />
              </el-icon>
              <div class="upload-text">添加轮播</div>
            </div>
          </el-upload>
        </div>
      </el-form-item>

      <!-- 价格 -->
      <el-form-item label="价格" required prop="price">
        <el-input-number v-model="formData.price" placeholder="请输入商品价格" :min="0" :precision="2"
          style="width: 100%; max-width: 300px" />
      </el-form-item>

      <!-- 库存 -->
      <el-form-item label="库存" required prop="stock">
        <el-input-number v-model="formData.stock" placeholder="请输入商品库存" :min="0"
          style="width: 100%; max-width: 300px" />
      </el-form-item>

      <!-- 市场价格 -->
      <el-form-item label="市场价格" prop="marketPrice">
        <el-input-number v-model="formData.marketPrice" placeholder="请输入市场价格" :min="0" :precision="2"
          style="width: 100%; max-width: 300px" />
      </el-form-item>

      <!-- 虚拟销量 -->
      <el-form-item label="虚拟销量" prop="virtualSales">
        <el-input-number v-model="formData.virtualSales" placeholder="请输入虚拟销量" :min="0"
          style="width: 100%; max-width: 300px" />
      </el-form-item>

      <!-- 详情富文本 -->
      <el-form-item label="详情" prop="content">
        <div class="rich-editor-container">
          <!-- <el-input
            v-model="formData.content"
            type="textarea"
            placeholder="请输入商品详细信息，支持 HTML 格式"
            :rows="6"
            class="rich-textarea"
          />
          <div class="editor-tip">
            提示：可以输入 HTML 标签来丰富商品详情展示效果
          </div> -->
          <QuillEditor 
            ref="contentEditor" 
            style="height: 300px;" theme="snow" 
            toolbar="full" content-type="html"
            @update:content="setValue()"
            v-model="formData.content" />

        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '立即修改' : '立即添加' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
import instance from '../utils/request'
//获取分类数据
const cateData = ref([])
const contentEditor = ref(null)
const setValue = () => {
  formData.content = contentEditor.value.getHTML()
}

const getCateData = async () => {
  let res = await instance.get('Goods/goodsCategory')
  if (res.code == 200) {
    cateData.value = res.data
  }
}
onMounted(() => {
  getCateData()
})
const props = defineProps({
  productDialogVisible: {
    type: Boolean,
    default: false
  },
  editProductData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['closeProductDialog', 'submitProduct'])

// 响应式数据
const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)
const isEdit = ref(false)

// 表单数据
const formData = reactive({
  productName: '',
  category: '',
  description: '',
  productImage: '',
  carouselImages: [],
  price: 0,
  stock: 0,
  marketPrice: 0,
  virtualSales: 0,
  isOnSale: 1,
  isHot: 0,
  isNew: 0,
  isPremium: 0,
  content: ''
})

// 表单验证规则
const rules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 50, message: '商品名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, max: 200, message: '商品描述长度在 10 到 200 个字符', trigger: 'blur' }
  ],
  productImage: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '商品价格必须大于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
  ]
}

// 监听父组件传递的显示状态
watch(() => props.productDialogVisible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    // 判断是编辑还是新增
    isEdit.value = !!props.editProductData
    if (isEdit.value) {
      // 编辑模式，填充数据
      Object.assign(formData, {
        ...props.editProductData,
        carouselImages: props.editProductData.carouselImages || []
      })
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  }
}, { immediate: true })

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    productName: '',
    category: '',
    description: '',
    productImage: '',
    carouselImages: [],
    price: 0,
    stock: 0,
    marketPrice: 0,
    virtualSales: 0,
    isOnSale: 1,
    isHot: 0,
    isNew: 0,
    isPremium: 0,
    content: ''
  })
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 主图上传处理
const handleMainImageChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.productImage = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 轮播图上传处理
const handleCarouselImageChange = (file) => {
  if (formData.carouselImages.length >= 5) {
    ElMessage.warning('最多只能上传5张轮播图')
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    formData.carouselImages.push(e.target.result)
  }
  reader.readAsDataURL(file.raw)
}

// 删除轮播图
const removeCarouselImage = (index) => {
  formData.carouselImages.splice(index, 1)
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG/WEBP 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交表单
const handleSubmit = async () => {
  console.log(formData.content, "88888");

  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 模拟提交数据
    setTimeout(() => {
      const message = isEdit.value ? '商品修改成功!' : '商品添加成功!'
      ElMessage.success(message)
      emit('submitProduct', { ...formData })
      submitLoading.value = false
      handleClose()
    }, 1000)

  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 取消操作
const handleCancel = () => {
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  emit('closeProductDialog')
  if (!isEdit.value) {
    resetForm()
  }
}
</script>

<style lang="scss" scoped>
.product-dialog {
  :deep(.el-dialog) {
    margin: 5vh auto;
    max-width: 600px;
    width: 90%;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
    overflow-x: hidden;
  }

  .product-form {
    max-height: 70vh;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 10px;
    box-sizing: border-box;
    width: 100%;

    .image-upload-container {
      .image-uploader {
        :deep(.el-upload) {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          transition: all 0.3s;

          &:hover {
            border-color: #409eff;
          }
        }
      }

      .upload-area {
        width: 120px;
        height: 120px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #8c939d;
        font-size: 14px;



        .upload-icon {
          font-size: 28px;
          margin-bottom: 8px;
        }

        .upload-text {
          font-size: 12px;
        }
      }

      .uploaded-image {
        width: 120px;
        height: 120px;
        object-fit: cover;
        border-radius: 6px;
      }
    }

    .carousel-upload-container {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;

      .carousel-images {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }

      .carousel-item {
        position: relative;

        .carousel-image {
          width: 120px;
          height: 120px;
          object-fit: cover;
          border-radius: 6px;
          border: 1px solid #dcdfe6;
        }

        .carousel-overlay {
          position: absolute;
          top: 0;
          right: 0;
          width: 24px;
          height: 24px;
          background: rgba(0, 0, 0, 0.5);
          border-radius: 0 6px 0 6px;
          display: flex;
          align-items: center;
          justify-content: center;

          .remove-icon {
            color: white;
            font-size: 14px;
            cursor: pointer;
          }
        }
      }

      .carousel-uploader {
        :deep(.el-upload) {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          transition: all 0.3s;

          &:hover {
            border-color: #409eff;
          }
        }
      }
    }

    .rich-editor-container {
      width: 100%;

      .rich-textarea {
        width: 100%;

        :deep(.el-textarea__inner) {
          resize: vertical;
        }
      }

      .editor-tip {
        font-size: 12px;
        color: #909399;
        margin-top: 5px;
      }
    }

    // 确保所有输入组件不超出容器宽度
    :deep(.el-input),
    :deep(.el-select),
    :deep(.el-textarea),
    :deep(.el-input-number) {
      max-width: 100%;
      box-sizing: border-box;
    }

    :deep(.el-form-item__content) {
      overflow: hidden;
    }
  }
}

.dialog-footer {
  text-align: right;

  .el-button {
    margin-left: 10px;
  }
}

// 必填项红色星号样式
:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

// 自定义滚动条样式
.product-form::-webkit-scrollbar {
  width: 6px;
}

.product-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.product-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.product-form::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>